package main

import (
	"fmt"
	"log"

	// "github.com/nareix/joy4/av"
	"github.com/nareix/joy4/av/avutil"
	"github.com/nareix/joy4/format"
	"github.com/nareix/joy4/format/rtmp"
)

func init() {
	format.RegisterAll()
}

func main() {
	// RTMP流地址
	rtmpUrl := "rtmp://172.31.100.201/meeting/922b0edb8a944264befbca5d9e10b3f2?streamToken=8678396fcc2c417cbc687eb2f85a044e"
	outputPath := "output.flv"

	// 连接RTMP流
	fmt.Println("连接RTMP流...")
	rtmpConn, err := rtmp.Dial(rtmpUrl)
	if err != nil {
		log.Fatalf("Error connecting to RTMP stream: %v", err)
	}
	defer rtmpConn.Close()
	fmt.Println("成功连接到RTMP流")

	// 获取流信息
	streams, err := rtmpConn.Streams()
	if err != nil {
		log.Fatalf("Error getting streams: %v", err)
	}

	// 打印流信息
	fmt.Println("流信息:")
	for i, stream := range streams {
		fmt.Printf("Stream %d: Type=%v\n", i, stream.Type())
	}

	// 创建输出文件
	outFile, err := avutil.Create(outputPath)
	if err != nil {
		log.Fatalf("Error creating output file: %v", err)
	}
	defer outFile.Close()

	// 设置计数器
	packetCount := 0
	maxPackets := 1000 // 设置最大包数，可以根据需要调整

	fmt.Println("开始读取数据包...")

	// 读取数据包
	for packetCount < maxPackets {
		packet, err := rtmpConn.ReadPacket()
		if err != nil {
			// if err == av.EOF {
			// 	fmt.Println("到达流末尾")
			// 	break
			// }
			log.Fatalf("读取数据包错误: %v", err)
		}

		// 写入数据包到文件
		err = outFile.WritePacket(packet)
		if err != nil {
			log.Fatalf("写入数据包错误: %v", err)
		}

		packetCount++
		if packetCount%100 == 0 {
			fmt.Printf("已处理 %d 个数据包\n", packetCount)
		}
	}

	fmt.Printf("完成! 共处理了 %d 个数据包\n", packetCount)
	fmt.Printf("输出文件保存在: %s\n", outputPath)
}
